//
//  LBMediaPresentViewController.m
//  LangBa
//
//  Created by Mac on 2017/12/21.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "MCAreaPickerViewController.h"
@interface MCAreaPickerViewController ()<UIPickerViewDelegate,UIPickerViewDataSource>
@property(nonatomic, strong) STButton                     *clearButton;
@property(nonatomic, strong) UIView                     *customView;
@property(nonatomic, strong) UIPickerView                     *pickerView;/**< pickerView */

@property(nonatomic, strong) NSMutableArray                     *provenceArray;/**< city */
@property(nonatomic, strong) NSMutableArray                     *cityArray;/**< city */
@end

@implementation MCAreaPickerViewController

- (instancetype)init
{
    if (self == [super init]) {
        self.modalPresentationStyle = UIModalPresentationOverFullScreen;
    }
    return self;
}
#pragma mark --vc 生命周期
- (void)viewDidLoad{
    [super viewDidLoad];
    [self configSubView];
    [self sendProvensRequest];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self show];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    self.clearButton = [[STButton alloc] initWithFrame:UIScreenFrame
                                                 title:nil
                                            titleColor:nil
                                             titleFont:0
                                          cornerRadius:0
                                       backgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.4]
                                       backgroundImage:nil
                                                 image:nil];
    [weakSelf.clearButton setClicAction:^(UIButton *sender) {
        [weakSelf dismiss];
    }];
    [self.view addSubview:_clearButton];
    
    self.customView = [[UIView alloc] initWithFrame:CGRectMake(0, UIScreenHeight, UIScreenWidth, 100)];
    self.customView.centerX = UIScreenWidth / 2;
    self.customView.top = UIScreenHeight;
    self.customView.backgroundColor = [UIColor whiteColor];
    self.customView.layer.cornerRadius = 0;
    self.customView.clipsToBounds = YES;
    self.customView.centerY = UIScreenHeight / 2;
    [self.view addSubview:self.customView];
    
    STButton * cancleButton = [[STButton alloc] initWithFrame:CGRectMake(15, 0, 60, 44)
                                                     title:@"取消"
                                                titleColor:SecendTextColor
                                                 titleFont:14
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:nil];
    [cancleButton setClicAction:^(UIButton *sender) {
        [weakSelf dismiss];
    }];
    [self.customView addSubview:cancleButton];
    
    
    STButton * confimButton = [[STButton alloc] initWithFrame:CGRectMake(15, 0, 60, 44)
                                                        title:@"确认"
                                                   titleColor:TM_ThemeBackGroundColor
                                                    titleFont:14
                                                 cornerRadius:0
                                              backgroundColor:nil
                                              backgroundImage:nil
                                                        image:nil];
    [confimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlectedConfimButton];
    }];
    confimButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    confimButton.right = UIScreenWidth - 15;
    [self.customView addSubview:confimButton];
    
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(15, confimButton.bottom+20, UIScreenWidth - 30, 250)];
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    self.pickerView.backgroundColor = UIColor.whiteColor;
    [self.customView addSubview:self.pickerView];
    
    self.customView.height = self.pickerView.bottom + 20;
    self.customView.top = UIScreenHeight;
    
}

#pragma mark --Private Method
- (void)show{
    [UIView animateWithDuration:0.6
                          delay:0
         usingSpringWithDamping:0.6
          initialSpringVelocity:0.7
                        options:UIViewAnimationOptionLayoutSubviews
                     animations:^{
                         self.customView.bottom = UIScreenHeight;
                     } completion:^(BOOL finished) {
                         
                     }];
}
- (void)dismiss{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.25 animations:^{
        self.customView.top = UIScreenHeight;
        self.clearButton.alpha = 0;
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
}
- (void)dismissWithHandle:(void(^)())handle{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.25 animations:^{
        self.customView.top = UIScreenHeight;
        self.clearButton.alpha = 0;
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:^{
            if (handle) {
                handle();
            }
        }];
    }];
}
- (void)onSlectedConfimButton{
    NSInteger index = [self.pickerView selectedRowInComponent:0];
    NSDictionary * provenceDic = self.provenceArray[index];
    
    NSInteger index1 = [self.pickerView selectedRowInComponent:1];
    NSDictionary * cityDic = self.cityArray[index1];
    
    if (provenceDic && cityDic) {
        
        NSString * province = [provenceDic[@"area2"] description];
        NSString * provinceCode = [provenceDic[@"id"] description];
        NSString * city = [cityDic[@"area2"] description];
        NSString * cityCode = [cityDic[@"id"] description];
        [self dismissWithHandle:^{
            if (self.onSlectedHandle) {
                self.onSlectedHandle(province, provinceCode, city, cityCode);
            }
        }];

        
    }else{
        [SVProgressHUD showErrorWithStatus:@"请选择地址"];
    }
    
    
}
#pragma mark --UIPickerViewDelegate
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component == 0) {
        NSDictionary * dic = self.provenceArray[row];
        NSString * area = dic[@"area2"];
        return area;
    }
    NSDictionary * dic = self.cityArray[row];
    NSString * area = dic[@"area2"];
    return area;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (component == 0) {
        NSDictionary * dic = self.provenceArray[row];
        NSString * ids = dic[@"id"];
        self.cityArray = nil;
        [self.pickerView reloadComponent:1];
        [self sendCityRequestWithCode:ids];
    }
}
#pragma mark --UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 2;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) {
        return self.provenceArray.count;
    }
    return self.cityArray.count;
}
#pragma mark --Action Method

- (void)onSelectedCancleButton{
    
    [self dismiss];
    
}
- (void)onSelectedWhiteView{
    [self.view endEditing:YES];
}
#pragma mark --NetWork Method
- (void)sendProvensRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * paramDic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"/Rest/System/ajaxGetProvince"];
    DDLogInfo(@"url:%@",url);
    DDLogInfo(@"param:%@",paramDic);
    [[STNetWrokManger defaultClient] requestIgnoreSuccessWithPath:url
                                                           method:STHttpRequestTypePost
                                                       parameters:nil
                                                          success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                              [SVProgressHUD dismiss];
                                                              self.provenceArray = [NSMutableArray new];
                                                              
                                                              self.provenceArray = responseObject;
                                                              [self.pickerView reloadComponent:0];
                                                              [self.pickerView selectRow:0 inComponent:0 animated:YES];
                                                              DDLogInfo(@"%@请求成功:resp\n%@",url,responseObject);
                                                          } failure:^(NSString *stateCode, STError *error) {
                                                              [SVProgressHUD dismiss];
                                                              [SVProgressHUD showErrorWithStatus:error.desc];
                                                              DDLogError(@"\nurl:%@\nparam:%@\nreson:%@",url,paramDic,error.desc);
                                                          }];

}
- (void)sendCityRequestWithCode:(NSString*)code{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * paramDic = [NSMutableDictionary new];
    if (code.length) {
        [paramDic setObject:code forKey:@"province"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"/Rest/System/ajaxGetCity"];
    DDLogInfo(@"url:%@",url);
    DDLogInfo(@"param:%@",paramDic);
    [[STNetWrokManger defaultClient] requestIgnoreSuccessWithPath:url
                                                           method:STHttpRequestTypePost
                                                       parameters:paramDic
                                                          success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                              [SVProgressHUD dismiss];
                                                              self.cityArray = [NSMutableArray new];
                                                              
                                                              self.cityArray = responseObject;
                                                              [self.pickerView reloadComponent:1];
                                                              [self.pickerView selectRow:0 inComponent:1 animated:YES];
                                                              DDLogInfo(@"%@请求成功:resp\n%@",url,responseObject);
                                                          } failure:^(NSString *stateCode, STError *error) {
                                                              [SVProgressHUD dismiss];
                                                              [SVProgressHUD showErrorWithStatus:error.desc];
                                                              DDLogError(@"\nurl:%@\nparam:%@\nreson:%@",url,paramDic,error.desc);
                                                          }];
}
@end







